<?php

namespace App\Http\Controllers\Api\V1;
use App\Models\Activity;
use App\Models\ActivityRecord;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Api\V1\Resources\ActivityResource;
use App\Http\Controllers\Api\V1\Resources\ActivityRecordResource;
use Illuminate\Database\Eloquent\Builder;

class ActivitiesController extends Controller
{
	public function index()
	{

		$startTime = request()->start_time ?? Carbon::now();
		$endTime = request()->end_time ?? Carbon::now()->addDays(1);



		$accounts = Activity::query()
				->where(function (Builder $query) use ($startTime,$endTime) {
							$query->where('start_at',">=",$startTime)
							->Where('end_at',"<=",$endTime);
					})
				->orWhere(function (Builder $query) use ($startTime,$endTime) {
					$query->where('end_at', ">=",$startTime)
						->where('end_at','<=',$endTime);
					})

				->paginate();
	
				
		return ActivityResource::collection($accounts);
	}


	public function show($id)
	{
		$account = Activity::find($id);
		return new ActivityResource($account);
	}

	public function store()
	{
		$activityId = request()->activity_id;
		$user = request()->user();
		if($user->activities()->where("activity_id",$activityId)->first()){

			fail("无需重复报名");
		}
		
		$user->addActivity($activityId);

        return response()->json(['code' => 200]);
	}

	public function records()
	{
		$condition = request("condition");
		$user = request()->user();


		if($condition == "wqd"){

			$records = ActivityRecord::query()
						->join('activities','activities.id','activity_records.activity_id')
						->where("user_id",$user->id)
						->where("is_qd",false)
						->where('end_at',">=",Carbon::now())
						->orderByDesc("activity_records.id")
						->paginate();
	
		}elseif($condition == "yqd"){
			$records = ActivityRecord::query()
				->where("user_id",$user->id)
				->where("is_qd",true)
				->orderByDesc("id")
				->paginate();

		}elseif($condition == "ygq"){
			$records = ActivityRecord::query()
						->join('activities','activities.id','activity_records.activity_id')
						->where("user_id",$user->id)
						->where("is_qd",false)
						->where('end_at',"<",Carbon::now())
						->orderByDesc("activity_records.id")
						->paginate();

		}else{
			$records = ActivityRecord::query()
				->where("user_id",$user->id)
				->orderByDesc("id")
				->paginate();

		}
				
		return ActivityRecordResource::collection($records);
		
	}
}
